#include "log.h"
#include "file.h"

#ifndef LINUX
	#define SAFE_PRINTF(...)	    Printf(__VA_ARGS__);
#else
	#include <syslog.h>
	#define SAFE_PRINTF(...)		syslog(LOG_NOTICE, __VA_ARGS__)
#endif

Log::Log()
{
#ifdef LINUX
	openlog(LOG_FILE_NAME, LOG_PID, LOG_LOCAL0);
#endif
}

Log::~Log()
{
#ifdef LINUX
	closelog();
#endif
}

bool Log::Printf(char* strMsg, ...)
{
	char content[LOG_BUFFER_SIZE] = { 0 };

	va_list args;
	va_start(args, strMsg);
	vsnprintf(content, sizeof(content) - 1, strMsg, args);
	va_end(args);

	printf("%s", content);
	return WriteFile(LOG_FILE_NAME, content, strlen(content));
}

void Log::Logout(LOGLEVEL logLevel, char* file, int line, char* function, char* strMsg, ...)
{
	if(logLevel < LOG_LEVEL)
		return;

	string logType = "";
	switch(logLevel)
	{
	case LOG_LEVEL_WARNING:
		logType = "logType: WARNING, ";
		break;

	case LOG_LEVEL_ERROR:
		logType = "logType: ERROR, ";
		break;

	default:
		logType = "logType: UNKNOWN, ";
		break;
	}

	string log;
	log += logType;

	time_t now = time(NULL);
	const int TIME_LEN = 255;
	char time_stamp[TIME_LEN] = { 0 };
	strftime(time_stamp, sizeof(time_stamp), "GMT[%Y-%m-%d %H:%M:%S] ", gmtime(&now));

#ifdef WIN32
	snprintf(&time_stamp[strlen(time_stamp)], TIME_LEN - strlen(time_stamp) - 1, "FILE: %s, LINE: %u, FUN: %s, ", strrchr(file, '\\') + 1, line, function);
#else
	snprintf(&time_stamp[strlen(time_stamp)], TIME_LEN - strlen(time_stamp) - 1, "FILE: %s, LINE: %u, FUN: %s, ", strrchr(file, '/') + 1, line, function);
#endif

	log += time_stamp;

	va_list args;
	va_start(args, strMsg);
	char content[LOG_BUFFER_SIZE] = { 0 };
	vsnprintf(content, sizeof(content) - 1, strMsg, args);
	va_end(args);

	log += content;

	SAFE_PRINTF("%s", log.c_str());
}